// pages/new-pages/talent-search/talent-search.js
import Toast from '../../../component/toast/toast';
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        resumeList: [],
        jobList: [],
        pageSize: 10,
        pageIndex: -1,
        hasMore: false,
        flag: 0,
        value:'',
        parmas:null,
        historyKey:'history',
        historyArr:[],
        showHistory:true
    },
    // 搜索框有焦点时
    searchFocus(e){
        this.setData({
            showHistory:true
        })
    },
    myCatchTouch(e){
        
    },
    /**
     * 搜索事件
     */
    searchConfirm(e) {
        let value = (e.detail.value+"").trim();
        this.setData({
            value: value
        })
        let data = this.joinData(false);
        this.queryResumes(data)
        this.saveHistory(value);
    },
    //保存信息到历史记录
    saveHistory(value){
        if(value){
            let historyKey = this.data.historyKey
            try {
                let history = wx.getStorageSync(historyKey)
                if (history) {
                    console.log("存在记录："+history);
                    //去重
                    let hasValue = history.find((item)=> Object.is(item , value))
                    if(hasValue){
                        return;
                    }
                }else{
                    console.log('不存在记录');
                    history = []
                } 
                //判断记录是否大于10个
                if(history.length >= 10){
                  history.splice(0 , 1)
                }
                history.push(value);
                wx.setStorageSync(historyKey, history)
                //更新数据
                this.setData({
                    historyArr:history
                })
            } catch (e) {
                // Do something when catch error
            }
        }
    },
    //获取搜索记录
    getSearchHistory(){
        try {
            var value = wx.getStorageSync(this.data.historyKey)
            if (value) {
                console.log('getSearchHistory' , value)
                this.setData({
                    historyArr:value
                })
            }
        } catch (e) {
            // Do something when catch error
        }
    },
    //清除搜索记录
    clearHistory(){
        try {
            wx.clearStorageSync()
            this.setData({
                historyArr:[]
            })
        } catch (e) {
            // Do something when catch error
        }
    },
    //点击搜索历史条目
    clickHisItem(e){
        let index = e.currentTarget.dataset.index;
        let value = this.data.historyArr[index]
        this.setData({
            value:value
        })
        let data = this.joinData(false);
        this.queryResumes(data)
    },
    //拼接参数
    joinData(isReach) {
        let pageI = ++this.data.pageIndex;
        if (!isReach) {
            pageI = 0;
            this.setData({
                hasMore: true
            });
            wx.showLoading({
                title: '加载中...',
                mask: true
            });
        }
        this.setData({
            pageIndex: pageI
        })
        let _data = this.data.parmas
        if(_data){
            _data.pageIndex = pageI
            return _data
        }
        return {
            experienceId: "",
            educationId: "",
            experienceMin: '-1',
            experienceMax: '-1',
            currentUserInfoId: '',
            positionId: '',
            salaryMin: '0',
            salaryMax: '0',
            pageSize: this.data.pageSize,
            pageIndex: pageI,
            keyword: this.data.value
        };
    },
    //简历检索
    queryResumes(data, isReach = false) {
        let that = this
        if (!that.data.hasMore) return;
        console.log(data)
        wx.request({
            url: app.globalData.serverAddress.getQueryResumes,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data: data,
            method: 'GET',
            success: function(res) {
                console.log("getQueryResumes response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let resumeList = res.data.BodyContent.List;
                        let count = res.data.BodyContent.TotalCount;
                        let flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        resumeList.forEach(function(arr, index) {
                            let city = resumeList[index].City;
                            if (city) {
                              resumeList[index].City = city.substr(0, city.length - 1);
                            }
                        });
                        if (isReach) {
                            resumeList = that.data.resumeList.concat(resumeList);
                        }
                        that.setData({
                            resumeList: resumeList,
                            hasMore: flag,
                            showHistory:false
                        })
                    }
                    else if(res.data.CodeStatus == 40005){
                        that.setData({
                            hasMore: false,
                            showHistory: true
                        });
                        Toast('符合条件的人才马上就来，过几天再来看看哟~')
                    }
                    else {
                        that.setData({
                            resumeList: [],
                            hasMore: false,
                            showHistory: true
                        });
                        Toast(res.data.Message);
                    }
                }
            },
            fail: function(res) {
                console.log("getQueryResumes fail", res);
            },
            complete: function(res) {
                wx.hideLoading();
            }
        });
    },
    //简历条目点击事件
    selectItem(e) {
      let index = e.currentTarget.dataset.index;
      let resumeId = this.data.resumeList[index].Id;
      wx.navigateTo({
        url: '/pages/new-pages/resume-detail/resume-detail?resumeId=' + resumeId
      });
        // if (this.data.flag == 0) {
        //     if (this.checkStatus()) {
        //         let index = e.currentTarget.dataset.index;
        //         let parmas = {
        //             jobId: this.data.jobList[index].Id,
        //             jobName: this.data.jobList[index].JobName,
        //             flag: 2
        //         }
        //         wx.navigateTo({
        //             url: '/pages/compony-pages/job-detail/job-detail?parmas=' + JSON.stringify(parmas)
        //         });
        //     }
        // } else {
        //     let index = e.currentTarget.dataset.index;
        //     let resumeId = this.data.resumeList[index].Id;
        //     wx.navigateTo({
        //         url: '/pages/new-pages/resume-detail/resume-detail?resumeId=' + resumeId
        //     });
        // }
    },
    //点击评估条目
    clickItemEvaluate(e) {
        let index = e.currentTarget.dataset.index;
        let name = this.data.resumeList[index].Name
        wx.navigateTo({
            url: '/pages/new-pages/evaluate-pass/evaluate-pass?name=' + name
        })
    },
    checkStatus() {
        if (!app.globalData.isLogin) {
            Toast("请先登录");
            return false;
        }
        return true;
    },
    getJobs(data, isReach = false) {
        let that = this
        if (!that.data.hasMore) return;
        wx.request({
            url: app.globalData.serverAddress.getQueryJobs,
            header: {
                'Authorization': "Bearer " + app.globalData.token
            },
            data: data,
            method: 'GET',
            success: function(res) {
                console.log("getQueryJobs response", res);
                if (res.statusCode == 200) {
                    if (res.data.CodeStatus == 20000) {
                        let jobList = res.data.BodyContent.List;
                        let count = res.data.BodyContent.TotalCount;
                        let flag = (that.data.pageIndex + 1) * that.data.pageSize < count;
                        jobList.forEach(function(arr, index) {
                            jobList[index].salaryTime = parseInt((arr.SalaryMin * 1000) / 80);
                        });
                        if (isReach) {
                            jobList = that.data.jobList.concat(jobList);
                        }
                        that.setData({
                            jobList: jobList,
                            hasMore: flag
                        })
                    } else {
                        that.setData({
                            jobList: [],
                            hasMore: false
                        });
                        Toast(res.data.Message);
                    }
                }
            },
            fail: function(res) {
                console.log("getQueryJobs fail", res);
            },
            complete: function(res) {
                wx.hideLoading();
                wx.stopPullDownRefresh();
            }
        });
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        // this.setData({
        //     flag:parseInt(options.flag)
        // })
        if (options.flag) {
            let data = JSON.parse(options.obj)
            this.setData({
                flag: parseInt(options.flag),
                parmas: data,
                showHistory: false
            })
            wx.setNavigationBarTitle({
              title: options.flag == 1 ? '热门人才' : '人才'
            })
            this.joinData(false)
            this.queryResumes(data)
        }else{
            this.getSearchHistory();
        }
        if(options.index){
            let title = '';
            switch(options.index){
                case '1': 
                    title = '美工设计'
                    break;
                case '2': 
                    title = '文案策划'
                    break;
                case '3': 
                    title = '客服运营'
                    break;
                case '4': 
                    title ='闪电开工'
                    break;
            }
            wx.setNavigationBarTitle({
                title: title
            })
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function() {
        let data = this.joinData(true);
        this.queryResumes(data, true)
        // if (this.data.flag == 0) {
        //     this.getJobs(data, true)
        // } else {
        //     this.queryResumes(data, true)
        // }

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {

    }
})